package vip.liux.front.application.clients;

import jakarta.annotation.Resource;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import vip.liux.users.IExternalUserLookupServiceProvider;
import vip.liux.users.IUserData;
import vip.liux.users.UserData;

import java.util.List;
import java.util.UUID;

import static vip.liux.front.application.clients.UserLookupAppServiceClient.TOKEN_CACHE;

// @Component
public class HttpClientExternalUserLookupServiceProvider implements IExternalUserLookupServiceProvider<UUID> {


    private final UserLookupAppServiceClient userLookupAppServiceClient;

    private static final Logger logger = LoggerFactory.getLogger(HttpClientExternalUserLookupServiceProvider.class);

    @Resource
    private RestTemplate restTemplate;

    public HttpClientExternalUserLookupServiceProvider(UserLookupAppServiceClient userLookupAppServiceClient) {
        this.userLookupAppServiceClient = userLookupAppServiceClient;
    }

    @Override
    public IUserData<UUID> findById(String id) {
        return userLookupAppServiceClient.findById(id);
    }

    @Override
    public IUserData<UUID> findByUsername(String username) {
        return userLookupAppServiceClient.findByUsername(username);
    }

    @Override
    public List<IUserData<UUID>> search(String sorting, String filter, int maxResultCount, int skipCount) {
        List<UserData<UUID>> items = userLookupAppServiceClient.search(new UserLookupAppServiceClient.UserLookupSearchInputDto(sorting, filter, maxResultCount, skipCount)).getItems();
        return items.stream().map(item -> (IUserData<UUID>) item).toList();
    }

    @Override
    public long count(String filter) {
        return userLookupAppServiceClient.count(new UserLookupAppServiceClient.UserLookupSearchInputDto(filter));
    }

    @Data
    public static class TokenModel {

        private String access_token;

        private String token_type;

        private long expires_in;

        private String scope;
    }


    @Scheduled(fixedDelay = 1000 * 60 * 60 * 7)
    public void getAccessToken() {
        // Create form data
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("client_id", "chat-service-client");
        formData.add("client_secret", "1q2w3e*");
        formData.add("grant_type", "client_credentials");
        formData.add("scope", "InternalGateway.Host Identity.Host");

        // Set headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // Create HttpEntity
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);


        ResponseEntity<TokenModel> responseEntity = restTemplate
                .exchange("https://auth.liux.vip/connect/token", HttpMethod.POST, requestEntity, TokenModel.class);

        TokenModel bodyString = responseEntity.getBody();

        TOKEN_CACHE.put("token", bodyString);

        logger.info("get access token, bodyString: {}", bodyString);
    }
}
